//go:build !no_check_ptrace
// +build !no_check_ptrace

/*
Copyright 2022 The Authors of https://github.com/CDK-TEAM/CDK .

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package escaping

import (
	"io/ioutil"
	"log"
	"regexp"
	"strconv"

	"github.com/cdk-team/CDK/pkg/exploit/base"
	"github.com/cdk-team/CDK/pkg/plugin"
	"github.com/cdk-team/CDK/pkg/tool/ps"
)

const sysPtraceCapMask uint64 = 2 << 18

func enableSysPtraceCap(mask uint64) bool {
	return mask&sysPtraceCapMask != 0
}

func CheckPidInject() bool {
	data, err := ioutil.ReadFile("/proc/self/status")
	if err != nil {
		log.Println(err)
		return false
	}

	pattern := regexp.MustCompile("(?i)capeff:\\s*?([a-z0-9]+)\\s")
	params := pattern.FindAllStringSubmatch(string(data), 1)

	for _, matched := range params {
		mask, err := strconv.ParseUint(matched[1], 16, 64)
		if err != nil {
			log.Println(err)
			return false
		}
		if enableSysPtraceCap(mask) {
			log.Println("SYS_PTRACE capability was enabled.")
			ps.RunPs()
			return true
		} else {
			log.Println("SYS_PTRACE capability was disabled.")
			return false
		}
	}
	return false
}

// plugin interface
type PidInject struct{ base.BaseExploit }

func (p PidInject) Desc() string {
	return "check if pid injection works with cap=SYS_PTRACE. usage: ./cdk run check-ptrace"
}
func (p PidInject) Run() bool {
	CheckPidInject()
	return true
}

func init() {
	exploit := PidInject{}
	exploit.ExploitType = "escaping"
	plugin.RegisterExploit("check-ptrace", exploit)
}
